<script setup>
import Toast from '@vant/weapp/dist/toast/toast';
import newLoading from '@/components/newLoading/index.vue';
import { imgUploadVerify } from '@/utils/auth'
import { getCategoryDetail } from '@/api/home'
import { imgHDrepair, editImgUpload, getImageByTaskId } from '@/api/painting';


import { ref } from 'vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';

// 页面携带参数
const queryItem = ref({})

// 查询详情信息
const queryInfo = ref({})

// 页面参数
const queryParams = ref({
  imageFileUrl: '',
})

// 提交数据
const queryData = ref({
  type: 'face',
  fixFaceOnly: 0, // 是否只修复人脸 0:处理整张图片， 1:只处理人脸
})

// 消耗算力
const expendNum = ref(0)

const loading = ref(false);
const loadingRef = ref(null)

// 任务id
const taskId = ref('')
// 定时器
let timer = null



// 立即生成
async function startFn() {
  clearInterval(timer);
  await verifyFn()
  loading.value = true
  await editImgUploadFn()
  imgHDrepairFn()
}




// 校验方法
function verifyFn() {
  return new Promise((resolve, reject) => {
    if (!queryParams.value.imageFileUrl) {
      Toast.fail('请上传图片')
      return reject()
    }
    resolve()
  })
}





// 获取任务状态
async function getImageByTaskIdFn() {
  const res = await getImageByTaskId(taskId.value)
  if (res.data.state === 1) {
    clearInterval(timer);
    await loadingRef.value.completeLoading()
    res.data.title = queryInfo.value.title
    uni.navigateTo({
      url: `/newEditionDraw/recreationDrawResult/index?data=${JSON.stringify(res.data)}`
    })
  } else if (![3, 4].includes(res.data.state)) {
    clearInterval(timer);
    const errorMessage = res.data?.remark.split('失败原因：')[1]
    Toast.fail(errorMessage);
    loading.value = false
  }
}



// 一键高清任务提交
async function imgHDrepairFn() {
  try {
    const res = await imgHDrepair(queryData.value)
    taskId.value = res.data.taskId
    timer = setInterval(() => {
      getImageByTaskIdFn()
    }, 2000)
  } catch (error) {
    loading.value = false
  }
}





// 上传原图
async function editImgUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await editImgUpload({
        type: 3,
        orgImg: queryParams.value.imageFileUrl
      })
      queryData.value.imageFileUrl = res.orgImgUrl
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}




// 图片预览
function previewImageFn() {
  uni.previewImage({
    urls: [queryParams.value.imageFileUrl],
  });
}


// 相册选择
async function uploadImgFn() {
  const res = await imgUploadVerify()
  queryParams.value.imageFileUrl = res
}


// 获取分类详情
async function getCategoryDetailFn() {
  const res = await getCategoryDetail(queryItem.value.id)
  queryInfo.value = res.data
  dataConversion()
}




// 数据转换
function dataConversion() {
  queryInfo.value.categoryParam.forEach(item => {
    if (item.title === 'expendNum') {
      expendNum.value = item.data[0].title
    }
  })
}


// 加载关闭事件
function loadingClose() {
  clearInterval(timer);
}

onUnload(() => {
  clearInterval(timer);
  loading.value = false
})


onLoad((e) => {
  if (e.item) {
    queryItem.value = JSON.parse(e.item)
    queryItem.value.imageFileUrl && (queryParams.value.imageFileUrl = queryItem.value.imageFileUrl)
  }
  getCategoryDetailFn()
})

defineExpose({
  uploadImgFn,
})
</script>

<template>
  <div class='highQualityPic'>
    <NavBar>{{ queryInfo?.title }}</NavBar>
    <div class="container">
      <div class="img_box">
        <!--上传按钮-->
        <div v-if="!queryParams.imageFileUrl" class="uploadImgBtn" @click="uploadImgFn">
          <i class="iconfont ai-icon-xiangcexuanze"></i>
          相册选择
        </div>
        <!--重新上传-->
        <div v-else class="upload_box" @click.stop="uploadImgFn">
          <i class="iconfont ai-icon-refresh"></i>
          重新上传
        </div>


        <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" alt="" class="imgSty" mode="aspectFit"
          @click="previewImageFn">
      </div>
    </div>

    <div class="footer">
      <div class="footer_placeholder"></div>
      <div class="footer_content">
        <myDrawButton :expendNum="expendNum" @click="startFn">一键高清</myDrawButton>
      </div>
    </div>
  </div>
  <van-toast id="van-toast" />
  <newLoading ref="loadingRef" v-model="loading" :duration="10000" :label="['排队中，预计等待15秒钟']" @close="loadingClose">
  </newLoading>
</template>

<style lang='scss' scoped>
.highQualityPic {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .container {
    box-sizing: border-box;
    flex: 1;
    padding: 30rpx;
    display: flex;
    flex-direction: column;

    .img_box {
      flex: 1;
      border-radius: 20rpx;
      background-color: var(--a-main-box-bg-color);
      position: relative;

      .uploadImgBtn {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 228rpx;
        height: 84rpx;
        border-radius: 45rpx;
        background-color: transparent;
        border: 3rpx solid var(--a-main-color);
        color: var(--a-one-text-color);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10rpx;
      }

      .upload_box {
        position: absolute;
        bottom: 20rpx;
        right: 20rpx;

        width: 84rpx;
        height: 84rpx;

        font-size: 16rpx;
        color: var(--a-one-text-color);
        border-radius: 13rpx;
        background: rgba(0, 0, 0, 0.6);

        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 5rpx;


        .iconfont {
          font-size: 36rpx;
        }
      }

      .imgSty {
        width: 100%;
        height: 100%;
      }
    }
  }

  .footer {
    .footer_placeholder {
      height: 176rpx;
    }

    .footer_content {
      box-sizing: border-box;
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 176rpx;
      background: #212142;
      padding: 28rpx 30rpx 0;
    }
  }
}
</style>